<template>
  <div class="doctor-dashboard">
    <el-container>
      <el-header class="dashboard-header">
        <div class="header-content">
          <h2>医生工作台</h2>
          <div class="user-info">
            <el-dropdown @command="handleCommand">
              <span class="user-dropdown">
                <el-avatar
                  :src="avatarUrlComputed"
                  :size="40"
                  @error="onAvatarError"
                />
                <span class="username">{{
                  doctorInfo.realName || doctorInfo.username
                }}</span>
                <el-icon><ArrowDown /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile"
                    >个人信息</el-dropdown-item
                  >
                  <el-dropdown-item command="avatar">更换头像</el-dropdown-item>
                  <el-dropdown-item command="logout" divided
                    >退出登录</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </el-header>

      <el-main class="dashboard-main">
        <!-- 欢迎横幅 -->
        <div class="welcome-banner">
          <div class="banner-content">
            <div class="welcome-text">
              <h1>
                欢迎回来，{{ doctorInfo.realName || doctorInfo.username }}医生
              </h1>
              <p>今天是 {{ getCurrentDate() }}，祝您工作愉快！</p>
            </div>
            <div class="banner-stats">
              <div class="stat-item">
                <div class="stat-number">{{ doctorInfo.points }}</div>
                <div class="stat-label">当前积分</div>
              </div>
            </div>
          </div>
        </div>

        <el-row :gutter="20">
          <!-- 个人信息卡片 -->
          <el-col :span="8">
            <el-card class="info-card" shadow="hover">
              <template #header>
                <div class="card-header">
                  <span class="card-title">
                    <el-icon><User /></el-icon>
                    个人信息
                  </span>
                  <el-button type="primary" size="small" @click="editProfile"
                    >编辑</el-button
                  >
                </div>
              </template>
              <div class="profile-info">
                <div class="avatar-section">
                  <el-avatar
                    :src="avatarUrlComputed"
                    :size="80"
                    @error="onAvatarError"
                  />
                  <el-button
                    type="primary"
                    size="small"
                    class="upload-btn"
                    @click="showAvatarUpload = true"
                  >
                    更换头像
                  </el-button>
                </div>
                <div class="info-list">
                  <div class="info-item">
                    <span class="label">用户名：</span>
                    <span class="value">{{ doctorInfo.username }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">姓名：</span>
                    <span class="value">{{
                      doctorInfo.realName || "未设置"
                    }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">邮箱：</span>
                    <span class="value">{{ doctorInfo.email }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">电话：</span>
                    <span class="value">{{
                      doctorInfo.phone || "未设置"
                    }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">性别：</span>
                    <span class="value">{{
                      getGenderText(doctorInfo.gender)
                    }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">执业范围：</span>
                    <span class="value">{{
                      doctorInfo.practiceScope || "未设置"
                    }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">积分：</span>
                    <span class="value">{{ doctorInfo.points }}</span>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>

          <!-- 统计信息卡片 -->
          <el-col :span="8">
            <el-card class="stats-card" shadow="hover">
              <template #header>
                <div class="card-header">
                  <span class="card-title">
                    <el-icon><DataAnalysis /></el-icon>
                    工作统计
                  </span>
                </div>
              </template>
              <div class="stats-content">
                <div class="stat-item">
                  <div class="stat-number">{{ workStatistics.totalActivities }}</div>
                  <div class="stat-label">活动总数</div>
                </div>
                <div class="stat-item">
                  <div class="stat-number">{{ workStatistics.healthRecords }}</div>
                  <div class="stat-label">健康档案</div>
                </div>
              </div>
            </el-card>
          </el-col>

          <!-- 快捷操作卡片 -->
          <el-col :span="8">
            <el-card class="action-card" shadow="hover">
              <template #header>
                <div class="card-header">
                  <span class="card-title">
                    <el-icon><Operation /></el-icon>
                    快捷操作
                  </span>
                </div>
              </template>
              <div class="action-content">
                <el-button
                  type="warning"
                  size="large"
                  class="action-btn"
                  @click="goToActivities"
                >
                  <el-icon><Calendar /></el-icon>
                  活动管理
                </el-button>
                <el-button
                  type="success"
                  size="large"
                  class="action-btn"
                  @click="goToHealthRecords"
                >
                  <el-icon><Document /></el-icon>
                  健康档案管理
                </el-button>
                <el-button
                  type="info"
                  size="large"
                  class="action-btn"
                  @click="goToStatistics"
                >
                  <el-icon><DataAnalysis /></el-icon>
                  数据统计
                </el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-main>
    </el-container>

    <!-- 头像上传对话框 -->
    <el-dialog
      v-model="showAvatarUpload"
      title="更换头像"
      width="400px"
      :close-on-click-modal="false"
    >
      <div class="avatar-upload">
        <el-upload
          ref="uploadRef"
          class="avatar-uploader"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :http-request="customUpload"
          accept=".jpg,.jpeg,.png,.gif,.bmp"
        >
          <img
            v-if="previewAvatarUrl"
            :src="previewAvatarUrl"
            class="avatar-preview"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <div class="upload-tips">
          <p>支持 jpg, jpeg, png, gif, bmp 格式</p>
          <p>文件大小不超过 5MB</p>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAvatarUpload = false">取消</el-button>
          <el-button
            type="primary"
            @click="confirmAvatarUpload"
            :loading="uploading"
          >
            确认上传
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  ArrowDown,
  Plus,
  Document,
  Calendar,
  User,
  DataAnalysis,
  Operation,
} from "@element-plus/icons-vue";
import {
  getDoctorInfo,
  getCurrentDoctorAvatar,
  uploadAvatar,
  getDoctorWorkStatistics,
} from "../api/doctor";
import {
  getAvatarUrl,
  getFullAvatarUrl,
  validateAvatarFile,
  createAvatarPreview,
  base64ToFile,
} from "../utils/avatarUtils";

const router = useRouter();
const showAvatarUpload = ref(false);
const uploading = ref(false);
const previewAvatarUrl = ref(""); // 预览用的头像URL
const uploadRef = ref();

// 工作统计数据
const workStatistics = ref({
  totalActivities: 0,
  healthRecords: 0
});

const doctorInfo = reactive({
  id: "",
  username: "",
  realName: "",
  phone: "",
  email: "",
  gender: null,
  birthDate: "",
  address: "",
  practiceScope: "",
  points: 0,
  level: 3,
  avatar: "",
  createTime: "",
});

// 获取医生信息
const fetchDoctorInfo = async () => {
  try {
    // 优先从本地存储获取医生信息
    const localDoctorInfo = localStorage.getItem("doctorInfo");
    if (localDoctorInfo) {
      try {
        const parsedInfo = JSON.parse(localDoctorInfo);
        Object.assign(doctorInfo, parsedInfo);
      } catch (e) {
        console.warn("本地存储的医生信息格式错误，重新获取");
      }
    }

    // 从后端获取最新的医生信息
    const response = await getDoctorInfo();
    if (response.code === 200) {
      Object.assign(doctorInfo, response.data);
      // 更新本地存储
      localStorage.setItem("doctorInfo", JSON.stringify(doctorInfo));

      // 获取完整的头像URL
      await fetchAvatarUrl();
    } else {
      ElMessage.error(response.message || "获取信息失败");
    }
  } catch (error) {
    console.error("获取医生信息失败:", error);
    ElMessage.error("获取信息失败，请检查网络连接");
  }
};

// 获取工作统计数据
const fetchWorkStatistics = async () => {
  try {
    const response = await getDoctorWorkStatistics();
    if (response.code === 200) {
      workStatistics.value = response.data;
    } else {
      console.warn("获取工作统计失败:", response.message);
    }
  } catch (error) {
    console.error("获取工作统计失败:", error);
  }
};

// 处理下拉菜单命令
const handleCommand = (command) => {
  switch (command) {
    case "profile":
      editProfile();
      break;
    case "avatar":
      showAvatarUpload.value = true;
      break;
    case "logout":
      logout();
      break;
  }
};

// 编辑个人信息
const editProfile = () => {
  ElMessage.info("个人信息编辑功能开发中...");
};

// 退出登录
const logout = async () => {
  try {
    await ElMessageBox.confirm("确定要退出登录吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    localStorage.removeItem("doctorToken");
    localStorage.removeItem("doctorInfo");
    ElMessage.success("已退出登录");
    router.push("/login");
  } catch {
    // 用户取消
  }
};

// 跳转到活动管理页面
const goToActivities = () => {
  router.push("/doctor-activities");
};

// 跳转到健康档案管理页面
const goToHealthRecords = () => {
  router.push("/doctor-health-records");
};

// 跳转到数据统计页面
const goToStatistics = () => {
  router.push("/doctor-health-statistics");
};

// 获取当前日期
const getCurrentDate = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  const weekdays = [
    "星期日",
    "星期一",
    "星期二",
    "星期三",
    "星期四",
    "星期五",
    "星期六",
  ];
  const weekday = weekdays[now.getDay()];
  return `${year}年${month}月${day}日 ${weekday}`;
};

// 获取性别文本
const getGenderText = (gender) => {
  if (gender === 1) return "男";
  if (gender === 2) return "女";
  return "未设置";
};

// 头像上传前的验证
const beforeAvatarUpload = async (file) => {
  // 使用工具函数验证文件
  if (!validateAvatarFile(file)) {
    ElMessage.error("文件格式或大小不符合要求");
    return false;
  }

  try {
    // 使用工具函数创建预览
    const preview = await createAvatarPreview(file);
    previewAvatarUrl.value = preview;
  } catch (error) {
    console.error("创建预览失败:", error);
    ElMessage.error("图片预览失败");
  }

  return false; // 阻止默认上传
};

// 头像URL状态
const avatarUrl = ref("");

// 获取头像URL - 使用API获取完整URL
const fetchAvatarUrl = async () => {
  try {
    console.log("开始获取头像URL...");
    const fullUrl = await getFullAvatarUrl();
    console.log("获取到的头像URL:", fullUrl);

    // 确保URL不为空且有效
    if (fullUrl && fullUrl !== "/default-avatar.png") {
      avatarUrl.value = fullUrl;
      console.log("设置avatarUrl.value为:", avatarUrl.value);
    } else {
      console.log("API返回的URL无效，使用本地处理方式");
      avatarUrl.value = getAvatarUrl(doctorInfo);
    }
  } catch (error) {
    console.error("获取头像URL失败:", error);
    // 如果API失败，使用本地处理方式作为备选
    avatarUrl.value = getAvatarUrl(doctorInfo);
  }
};

// 获取头像URL - 使用计算属性避免重复计算
const avatarUrlComputed = computed(() => {
  console.log("计算头像URL - avatarUrl.value:", avatarUrl.value);
  console.log("计算头像URL - doctorInfo.avatar:", doctorInfo.avatar);

  // 如果API获取的URL存在且有效，优先使用
  if (avatarUrl.value && avatarUrl.value !== "/default-avatar.png") {
    console.log("使用API获取的URL:", avatarUrl.value);
    return avatarUrl.value;
  }

  // 如果doctorInfo中有头像路径，使用本地处理方式
  if (
    doctorInfo.avatar &&
    doctorInfo.avatar !== "null" &&
    doctorInfo.avatar !== "undefined"
  ) {
    const localUrl = getAvatarUrl(doctorInfo);
    console.log("使用本地处理的URL:", localUrl);
    return localUrl;
  }

  // 最后使用默认头像
  console.log("使用默认头像");
  return getAvatarUrl(doctorInfo);
});

// 头像加载失败处理
const onAvatarError = (event) => {
  // 防止无限循环：如果已经是默认头像，就不再设置
  if (event.target && event.target.src !== "/default-avatar.png") {
    // 设置默认头像
    event.target.src = "/default-avatar.png";

    // 可选：更新doctorInfo中的avatar为空，避免下次渲染时再次尝试加载无效URL
    if (doctorInfo.avatar && doctorInfo.avatar !== "/default-avatar.png") {
      doctorInfo.avatar = "";
    }
  }
};

// 自定义上传
const customUpload = (options) => {
  // 这里只是预览，实际上传在确认按钮点击时进行
  // 移除不必要的console.log
};

// 确认头像上传
const confirmAvatarUpload = async () => {
  if (!previewAvatarUrl.value) {
    ElMessage.warning("请先选择图片");
    return;
  }

  try {
    uploading.value = true;

    // 使用工具函数将Base64转换为文件
    const file = base64ToFile(previewAvatarUrl.value, "avatar.jpg");

    // 创建FormData对象
    const formData = new FormData();
    formData.append("avatar", file);

    // 使用医生头像上传接口
    const uploadResponse = await uploadAvatar(formData);

    // 添加调试信息
    console.log("上传响应:", uploadResponse);

    if (uploadResponse.code === 200) {
      ElMessage.success("头像上传成功");

      // 医生头像上传接口返回的是avatarUrl字段
      const newAvatarUrl = uploadResponse.data?.avatarUrl;

      console.log("提取的头像URL:", newAvatarUrl);
      console.log("API响应数据结构:", uploadResponse.data);
      console.log("完整的API响应:", uploadResponse);

      if (newAvatarUrl) {
        // 将完整URL转换为相对路径存储到数据库
        // 例如：http://localhost:8080/picture/avatar/123.jpg -> avatar/123.jpg
        const relativePath = newAvatarUrl.replace(/^.*\/picture\//, "");
        doctorInfo.avatar = relativePath;
        // 更新本地存储的医生信息
        localStorage.setItem("doctorInfo", JSON.stringify(doctorInfo));

        console.log("更新后的医生信息:", doctorInfo);

        // 重新获取完整的头像URL
        await fetchAvatarUrl();

        // 强制组件重新渲染
        await nextTick();
      }

      showAvatarUpload.value = false;
      previewAvatarUrl.value = "";
    } else {
      ElMessage.error(uploadResponse.message || "上传失败");
    }
  } catch (error) {
    console.error("头像上传失败:", error);
    ElMessage.error("上传失败，请检查网络连接");
  } finally {
    uploading.value = false;
  }
};

// 组件挂载时获取医生信息
onMounted(() => {
  fetchDoctorInfo();
  fetchWorkStatistics();
});
</script>

<style scoped>
.doctor-dashboard {
  min-height: 100vh;
  background: linear-gradient(135deg, #4caf50 0%, #2e7d32 100%);
  background-attachment: fixed;
}

.dashboard-header {
  background-color: #fff;
  border-bottom: 1px solid #e4e7ed;
  padding: 0;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

.header-content h2 {
  margin: 0;
  color: #303133;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-dropdown {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 6px;
  transition: background-color 0.3s;
}

.user-dropdown:hover {
  background-color: #f5f7fa;
}

.username {
  margin: 0 8px;
  color: #303133;
  font-weight: 500;
}

.dashboard-main {
  padding: 20px;
}

.welcome-banner {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 30px;
  margin-bottom: 30px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.banner-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.welcome-text h1 {
  margin: 0 0 10px 0;
  color: #2c3e50;
  font-size: 28px;
  font-weight: 600;
}

.welcome-text p {
  margin: 0;
  color: #7f8c8d;
  font-size: 16px;
}

.banner-stats {
  display: flex;
  gap: 30px;
}

.banner-stats .stat-item {
  text-align: center;
  padding: 20px;
  background: linear-gradient(135deg, #23d732cc, #c4bfc8);
  border-radius: 12px;
  color: white;
  min-width: 120px;
}

.banner-stats .stat-number {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
  color: #2d08d2;
}

.banner-stats .stat-label {
  font-size: 14px;
  opacity: 0.9;
}

.info-card,
.stats-card,
.action-card {
  height: 100%;
  margin-bottom: 20px;
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.info-card:hover,
.stats-card:hover,
.action-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.profile-info {
  text-align: center;
}

.avatar-section {
  margin-bottom: 20px;
}

.upload-btn {
  margin-top: 10px;
}

.info-list {
  text-align: left;
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.label {
  color: #606266;
  font-weight: 500;
}

.value {
  color: #303133;
}

.stats-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.stat-item {
  text-align: center;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  color: #606266;
  font-size: 14px;
}

.stat-actions {
  margin-top: 20px;
  text-align: center;
}

.stat-actions .el-button {
  width: 100%;
  border-radius: 6px;
  font-weight: 500;
}

.action-content {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.action-btn {
  width: 100%;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.avatar-upload {
  text-align: center;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 150px;
  height: 150px;
  margin: 0 auto 20px;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.avatar-preview {
  width: 150px;
  height: 150px;
  display: block;
  object-fit: cover;
}

.upload-tips {
  color: #909399;
  font-size: 12px;
  line-height: 1.5;
}

.upload-tips p {
  margin: 5px 0;
}

.dialog-footer {
  text-align: right;
}
</style> 